package com.qyer.search.threading;

import java.text.DecimalFormat;
import java.util.UUID;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * User: Z J Wu Date: 2015/04/03 Time: 23:53 Package: com.qyer.dsp.threading
 */
public class GenericThreadThreadFactory implements ThreadFactory {

  private final String id;
  final ThreadGroup group;
  final AtomicInteger threadNumber = new AtomicInteger(1);
  final String namePrefix;

  public GenericThreadThreadFactory(String threadNamePrefix) {
    id = UUID.randomUUID().toString();
    SecurityManager s = System.getSecurityManager();
    group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
    namePrefix = threadNamePrefix + ".";
  }

  @Override public Thread newThread(Runnable r) {
    int tn = threadNumber.getAndIncrement();
    DecimalFormat df = new DecimalFormat("000");
    Thread t = new Thread(group, r, namePrefix + df.format(tn), 0);
    if (!t.isDaemon())
      t.setDaemon(true);
    if (t.getPriority() != Thread.NORM_PRIORITY)
      t.setPriority(Thread.NORM_PRIORITY);
    return t;
  }

  @Override public String toString() {
    return "DataPlatformThreadThreadFactory." + id + "." + threadNumber;
  }

}
